﻿using DocumentFormat.OpenXml.Lite.WordprocessingML;
using DocumentFormat.OpenXml.Lite.WordprocessingML.Word.Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using IO = System.IO;

namespace DocumentFormat.OpenXml.Lite.Core.Office
{
    public static class Extensions
    {
        public static Document CreateWordDocument(this DocumentManager manager)
        {
            Guid id = DocumentFS.DocumentFS.CreateSandbox();

            WordDocument doc = new WordDocument(id, DocumentType.Word);
            doc.CreateDefault();
            manager.AddDocument(id, doc);

            return doc.Document;
        }

        public static bool OpenWordDocument(this DocumentManager manager, string path, out Document document)
        {
            if (IO.Path.GetExtension(path) != ".docx")
            {
                throw new OpenXmlException("Unknown OOXML file extension: '" + IO.Path.GetExtension(path) + "'!");
            }

            using (IO.FileStream fs = IO.File.Open(path, IO.FileMode.Open))
            {
                document = manager.OpenWordDocument(fs);
                return document != null;
            }
        }

        public static Document OpenWordDocument(this DocumentManager manager, IO.Stream stream)
        {
            try
            {
                Guid id = DocumentFS.DocumentFS.CreateSandbox();
                DocumentBase docBase = new WordDocument(id, DocumentType.Excel);

                docBase.CreateDefault();
                manager.AddDocument(id, docBase);

                if (manager.OpenDocument(stream, docBase))
                {
                    return (docBase as WordDocument).Document;
                }
                return null;
            }
            catch (Exception ex)
            {
                throw new OpenXmlException("Cannot parse word document. See inner exception for details.", ex);
            }
        }
    }
}
